package com.wwe.kotlinstudy.util

/**
 * @name KotlinStudy
 * @package name：com.wwe.kotlinstudy.util
 * @anthor DavidZhang
 * @time 2018/4/17 14:27
 * @class describe
 */
class WhenStudy {

    fun test1(x: Int) {
        when (x) {
            1 -> print("x == 1")
            2 -> print("x == 2")
            else -> { // 注意这个块
                print("x is neither 1 nor 2")
            }
        }
    }

    /**如果很多分支需要用相同的方式处理，则可以把多个分支条件放在一起，用逗号分隔*/
    fun test2(x: Int) {
        when (x) {
            0, 1 -> print("x == 0 or x == 1")
            else -> print("otherwise")
        }
    }

    /**我们可以用任意表达式（而不只是常量）作为分支条件*/
    fun test3(x: String) {
        when (x) {
            "WWE" -> print("s encodes x")
            else -> print("s does not encode x")
        }
    }

    /**检测一个值在（in）或者不在（!in）一个区间或者集合中：*/
    fun test4(x: Int) {
        when (x) {
            in 1..10 -> print("x is in the range")
            !in 10..20 -> print("x is outside the range")
            else -> print("none of the above")
        }
    }

    /**Any其实就是Object类型*/
    fun hasPrefix(x: Any) = when (x) {
        is String -> x.startsWith("prefix")
        else -> false
    }

    /**when 也可以用来取代 if-else if链。*/
    fun test5(x: Int) {
        when {
            x > 1 -> print("I am Mizzy")
            x > 2 -> print("I am stone")
            else -> print("I am Big Show")
        }
    }

    fun test6(): String {
        val datas = listOf("apple", "banana", "pear")
        when {
            "apple" in datas -> return "yes"
            "juicy" in datas -> return "no"
        }
        return "Unkown"
    }

    fun test7(obj: Any): String =
            when (obj) {
                1 -> "one"
                "Hello" -> "Greeting"
                is Long -> "Long"
                else -> "Unkown"
            }


}